package com.youmingxing.adpter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.youmingxing.R;
import com.youmingxing.activity.ContentDetailActivity;
import com.youmingxing.activity.selfInfo.MyAuditionGoingActivity;
import com.youmingxing.activity.selfInfo.PersonalInfoActivity;
import com.youmingxing.bean.Content;
import com.youmingxing.bean.HighLight;
import com.youmingxing.network.AccountApi;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.utils.LogUtil;
import com.youmingxing.utils.TimeUtils;
import com.youmingxing.utils.Tools;
import com.youmingxing.view.DialogManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * @author evilyin(ChenZhixi)
 * @since 15/9/4
 */
public class ContentListAdapter extends BaseAdapter {

    private List<Content> mList = new ArrayList<>();
    private LayoutInflater inflater;
    private Context context;
    private ImageLoader imageLoader;
    public ContentListAdapter(Context ctx) {
        inflater = LayoutInflater.from(ctx);
        this.context = ctx;
        imageLoader = ImageLoader.getInstance();
    }
    public void setData(List<Content> list) {
        mList = list;
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    ViewHolder holder;
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ContentListener listener = new ContentListener(position);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.list_item_content, null);
            holder = new ViewHolder();
            holder.imageView = (ImageView) convertView.findViewById(R.id.content_image);
            holder.play = (ImageView) convertView.findViewById(R.id.content_video_play);
            holder.userHeadImg = (ImageView) convertView.findViewById(R.id.content_avatar);
            holder.title = (TextView) convertView.findViewById(R.id.content_title);
            holder.browseNumber = (TextView) convertView.findViewById(R.id.content_browse_number);
            holder.likeNumber = (TextView) convertView.findViewById(R.id.content_like_number);
            holder.commentNumber = (TextView) convertView.findViewById(R.id.content_comment_number);
            holder.actorName = (TextView) convertView.findViewById(R.id.content_actor_name);
            holder.identityImage = (ImageView) convertView.findViewById(R.id.authentication_img);

            holder.auditionType = (TextView) convertView.findViewById(R.id.content_audition_type);
            holder.comeonLayout = convertView.findViewById(R.id.content_comeon_layout);
            holder.ticket = (LinearLayout) convertView.findViewById(R.id.content_ticket_button);
            holder.isVerified = (ImageView) convertView.findViewById(R.id.is_auth);
            holder.deleteImg = (ImageView) convertView.findViewById(R.id.delete_img);
            holder.deleteBtn = convertView.findViewById(R.id.delete_btn);
            holder.notPassView = (TextView) convertView.findViewById(R.id.not_passed);
            holder.authenticationImg = (ImageView) convertView.findViewById(R.id.authentication_img);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Content thisContent = mList.get(position);
        if (thisContent.getType() == 1) {
            holder.play.setVisibility(View.GONE);
            Glide.with(context.getApplicationContext()).load(thisContent.getThumbnail()).placeholder(R
                    .drawable.default_16_9).error(R
                    .drawable.default_16_9).animate(R.anim.abc_fade_in).into(holder
                    .imageView);
        } else if (thisContent.getType() == 2) {
            holder.play.setVisibility(View.VISIBLE);
            if (!thisContent.getThumbnail().equals("")) {
                Glide.with(context).load(thisContent.getThumbnail()).placeholder(R
                        .drawable.default_16_9).error(R
                        .drawable.default_16_9).animate(R.anim.abc_fade_in).into(holder
                        .imageView);
                LogUtil.i("--------sectgetThumbnail----", " " + thisContent.getThumbnail());
//                final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
//                        , LinearLayout.LayoutParams.WRAP_CONTENT);
//                holder.imageView.setImageResource(R.drawable.default_16_9);
//                imageLoader.loadImage(thisContent.getThumbnail(), new SimpleImageLoadingListener() {
//                    @Override
//                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//                        // Do whatever you want with Bitmap
//                        holder.imageView.setImageBitmap(loadedImage);
//                        params.height = DisplayUtil.getScreenWidth() * loadedImage.getHeight() / loadedImage.getWidth();
//                        holder.imageView.setLayoutParams(params);
//                        holder.imageView.setAdjustViewBounds(true);
//                    }
//                });
            } else {
                holder.imageView.setImageResource(R.drawable.default_16_9);
            }
            holder.play.setOnClickListener(listener);
        }
        holder.imageView.setOnClickListener(listener);

        holder.title.setOnClickListener(listener);
        holder.browseNumber.setText(Tools.toK(thisContent.browse_num));
        holder.likeNumber.setText(Tools.toK(thisContent.getThumbsup_num()));
        holder.commentNumber.setText(Tools.toK(thisContent.getComment_num()));
        holder.actorName.setText(thisContent.getU_name());
        holder.actorName.setOnClickListener(listener);
        Glide.with(context).load(thisContent.getU_headimg()).placeholder(R.drawable
                .default_avatar).error(R.drawable.default_avatar)
                .bitmapTransform(new
                        CropCircleTransformation(context)).thumbnail(0.3f).into(holder.userHeadImg);
        holder.userHeadImg.setOnClickListener(listener);

        if (thisContent.getU_apply_id() != -1) {
            holder.comeonLayout.setVisibility(View.VISIBLE);
            holder.auditionType.setText(thisContent.u_apply_tip);
            holder.auditionType.setOnClickListener(listener);
            holder.ticket.setOnClickListener(listener);
        } else {
            holder.comeonLayout.setVisibility(View.GONE);
        }

//        LogUtil.i("------getUserMarkIcon--adapter---",thisContent.user_type + "---" + AllStarApi.getUserMarkIcon
//                (Integer.parseInt(thisContent.user_type)));
        Glide.with(context).load(AllStarApi.getUserMarkIcon
                (Integer.parseInt(thisContent.user_type))).
                crossFade().into(holder.authenticationImg );

        //是否显示删除
        if (thisContent.isShowDelete) {
            holder.deleteBtn.setClickable(true);
            holder.deleteBtn.setOnClickListener(listener);
            holder.deleteImg.setVisibility(View.VISIBLE);
        } else {
            holder.deleteBtn.setClickable(false);

            holder.deleteImg.setVisibility(View.INVISIBLE);
        }
        //是否审核通过
        if (thisContent.status == 2) {
            holder.notPassView.setVisibility(View.VISIBLE);
            holder.notPassView.setText("抱歉,您的作品没有通过审核" + "\n" + thisContent.reason);
        } else {
            holder.notPassView.setVisibility(View.GONE);
        }
        //活动内容
        SpannableString spStr = new SpannableString(thisContent.title);
        for (int i = 0; i < thisContent.highLights.size(); i++) {
            final HighLight highLight = thisContent.highLights.get(i);
            if (thisContent.title.contains(highLight.topic)) {
                int start = thisContent.title.indexOf(highLight.topic);
                int end = start + highLight.topic.length();
                spStr.setSpan(new ClickableSpan() {
                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(0xff507daf);       //设置文件颜色
                        ds.setUnderlineText(false);      //设置下划线
                    }

                    @Override
                    public void onClick(View widget) {
                        highLight.action.jump(context);
                    }
                }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        holder.title.setText(spStr);
        holder.title.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
        return convertView;
    }

    private class ViewHolder {
        ImageView imageView;
        ImageView play;
        ImageView userHeadImg;
        TextView title;
        TextView browseNumber;
        TextView likeNumber;
        TextView commentNumber;
        TextView actorName;
        TextView auditionType;
        View comeonLayout;
        LinearLayout ticket;
        ImageView isVerified;
        ImageView identityImage;
        private ImageView authenticationImg;
        ImageView deleteImg;
        View deleteBtn;
        TextView notPassView;
    }

    private class ContentListener implements View.OnClickListener {

        private int position;

        public ContentListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            final Intent intent;
            final Content content = mList.get(position);
            switch (v.getId()) {
                case R.id.content_image:
                case R.id.content_title:
                    if (content.status != 2) {
                        intent = new Intent(context, ContentDetailActivity.class);
                        intent.putExtra("content_id", content.getId());
                        context.startActivity(intent);
                    }
                    break;
                case R.id.content_video_play:
                    AccountApi.getVedioSign(new BaseJsonHandler(context) {
                        @Override
                        public void onSuccessWithData(JSONObject response) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            String url = mList.get(position).getUrl() + "?sign=" + response.optJSONObject
                                    ("data")
                                    .optString("sign");
                            intent.setDataAndType(Uri.parse(url), "video/*");
                            context.startActivity(intent);
                        }
                    });

                    break;
                case R.id.content_avatar:
                case R.id.content_actor_name:
                    intent = new Intent(context, PersonalInfoActivity.class);
                    intent.putExtra("u_id", mList.get(position).getU_id());
                    context.startActivity(intent);
                    break;
                case R.id.content_ticket_button:
                    DialogManager.showDialog(context, "正在提交");
                    AllStarApi.vote(mList.get(position).getU_apply_id(), 1, new BaseJsonHandler
                            (context) {
                        @Override
                        public void onSuccessWithData(JSONObject response) {
                            int result = response.optJSONObject("data").optInt("result");
                            switch (result) {
                                case 1:
                                    showToast("加油成功");
                                    break;
                                case 0:
                                    showToast("系统错误");
                                    break;
                                case 2:
                                    long time = response.optJSONObject("data").optLong("gen_duetime");
                                    AlertDialog.Builder builder = new AlertDialog.Builder
                                            (context);
                                    builder.setCancelable(false).setTitle("您的加油票不足1张").setMessage
                                            (TimeUtils.parseSecondToString(time) + "后,您将得到一张新票")
                                            .setPositiveButton("确定", null).show();
                                    break;
                            }
                        }
                    });
                    break;
                case R.id.content_audition_type:
                    intent = new Intent(context, MyAuditionGoingActivity.class);
                    intent.putExtra("id", mList.get(position).getU_apply_id());
                    context.startActivity(intent);
                    break;
                case R.id.delete_btn:
                    //删除
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle(R.string.delete_work_title).setMessage(R.string.delete_work_message)
                            .setPositiveButton(R.string.delete_work_yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    SelfInfoApi.deleteMyWorks(content.getId(), new BaseJsonHandler(context) {
                                        @Override
                                        public void onSuccessWithData(JSONObject response) {
                                            Toast.makeText(context, R.string.delete_work_success, Toast.LENGTH_SHORT).show();
                                            mList.remove(position);
                                            notifyDataSetChanged();
                                        }
                                    });
                                }
                            }).setNegativeButton(R.string.delete_work_no, null).show();

                    break;
                default:
                    break;
            }
        }
    }
}
